package com.tencent.qcloud.timchat.ui;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.activity.AdviserActivity;
import com.bxd.baodan.activity.LoginActivity;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.fragment.BaseFragment;
import com.bxd.baodan.item.RecommendAgentItem;
import com.bxd.baodan.item.RecommendAgentItem.DataItem.AgentBean;
import com.bxd.baodan.util.GlideUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.widget.MyListView;
import com.tencent.TIMConversation;
import com.tencent.TIMConversationType;
import com.tencent.TIMFriendFutureItem;
import com.tencent.TIMGroupCacheInfo;
import com.tencent.TIMMessage;
import com.tencent.qcloud.presentation.presenter.FriendshipManagerPresenter;
import com.tencent.qcloud.presentation.viewfeatures.ConversationView;
import com.tencent.qcloud.presentation.viewfeatures.FriendshipMessageView;
import com.tencent.qcloud.timchat.adapters.ConversationAdapter;
import com.tencent.qcloud.timchat.model.Conversation;
import com.tencent.qcloud.timchat.model.ConversationPresenter;
import com.tencent.qcloud.timchat.model.FriendshipConversation;
import com.tencent.qcloud.timchat.model.MessageFactory;
import com.tencent.qcloud.timchat.model.NomalConversation;
import com.tencent.qcloud.timchat.utils.PushUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * 会话列表界面
 */
public class ConversationFragment extends BaseFragment implements ConversationView, FriendshipMessageView, View.OnClickListener {

    private View view;
    private List<Conversation> conversationList = new LinkedList<>();
    private ConversationAdapter adapter;
    private MyListView listView;
    private ConversationPresenter presenter;
    private FriendshipManagerPresenter friendshipManagerPresenter;
    private List<String> groupList;
    private FriendshipConversation friendshipConversation;
    LinearLayout adviser_ly;
    boolean isPrepared = false;


    private MyListView adviserLv;
    private List<AgentBean> adviserList = new ArrayList<>();


    CommonAdapter adviserAdapter;
    View wendaLy;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_conversation, container, false);
            listView = (MyListView) view.findViewById(R.id.list);

            adviser_ly = (LinearLayout) view.findViewById(R.id.relative_top);



            wendaLy.setOnClickListener(this);
            wendaLy.setFocusable(true);
            wendaLy.setFocusableInTouchMode(true);
            wendaLy.requestFocus();


            adviserLv = (MyListView) view.findViewById(R.id.adviser_list);


            // TODO: 17/7/22 这个view是自己绘制的
            adapter = new ConversationAdapter(getActivity(), R.layout.conversation_item, conversationList);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //我的顾问 聊天点击
                    MobclickAgent.onEvent(App.getContext(), "v5_5_1_XX_ltjl");
                    conversationList.get(position).navToDetail(getActivity());

                }
            });


            friendshipManagerPresenter = new FriendshipManagerPresenter(this);
            presenter = new ConversationPresenter(this);
            presenter.getAgentConversation();
            registerForContextMenu(listView);


        }
        adapter.notifyDataSetChanged();
        refresh();
        return view;

    }

    public void reloadData() {
        //判断是切换账户后第一次resume

        if (presenter != null) {
            presenter.getAgentConversation();
        }
    }


    /**
     * 初始化界面或刷新界面
     *
     * @param conversationList
     */
    @Override
    public void initView(List<TIMConversation> conversationList) {
        this.conversationList.clear();
        groupList = new ArrayList<>();
        for (TIMConversation item : conversationList) {
            switch (item.getType()) {
                case C2C:
                case Group:
                    this.conversationList.add(new NomalConversation(item));
                    groupList.add(item.getPeer());
                    break;
            }
        }
        friendshipManagerPresenter.getFriendshipLastMessage();
    }

    /**
     * 更新最新消息显示
     *
     * @param message 最后一条消息
     */
    @Override
    public void updateMessage(TIMMessage message) {
        if (message == null) {
            adapter.notifyDataSetChanged();
            return;
        }
        if (message.getConversation().getType() == TIMConversationType.System) {
            return;
        }
        //        if (MessageFactory.getMessage(message) instanceof CustomMessage) return;
        NomalConversation conversation = new NomalConversation(message.getConversation());
        Iterator<Conversation> iterator = conversationList.iterator();
        while (iterator.hasNext()) {
            Conversation c = iterator.next();
            if (conversation.equals(c)) {
                conversation = (NomalConversation) c;
                iterator.remove();
                break;
            }
        }
        conversation.setLastMessage(MessageFactory.getMessage(message));
        conversationList.add(conversation);
        Collections.sort(conversationList);
        refresh();
    }

    /**
     * 更新好友关系链消息
     */
    @Override
    public void updateFriendshipMessage() {
        friendshipManagerPresenter.getFriendshipLastMessage();
    }

    /**
     * 删除会话
     *
     * @param identify
     */
    @Override
    public void removeConversation(String identify) {
        Iterator<Conversation> iterator = conversationList.iterator();
        while (iterator.hasNext()) {
            Conversation conversation = iterator.next();
            if (conversation.getIdentify() != null && conversation.getIdentify().equals(identify)) {
                iterator.remove();
                adapter.notifyDataSetChanged();
                return;
            }
        }
    }

    /**
     * 更新群信息
     *
     * @param info
     */
    @Override
    public void updateGroupInfo(TIMGroupCacheInfo info) {
        for (Conversation conversation : conversationList) {
            if (conversation.getIdentify() != null && conversation.getIdentify().equals(info.getGroupInfo().getGroupId())) {
                adapter.notifyDataSetChanged();
                return;
            }
        }
    }

    /**
     * 刷新
     */
    @Override
    public void refresh() {

        // TODO: 2017/4/5 添加提问
        if (LoginInfo.getInstance(App.getContext()).isLogin() && conversationList.size() != 0) {

            adviser_ly.setVisibility(View.GONE);
            Collections.sort(conversationList);

                requestNickName();


        } else {
            conversationList.clear();
            adviser_ly.setVisibility(View.VISIBLE);
            getAdviserList();
            // TODO: 17/7/23 显示顾问列表
        }




        adapter.hasUnRead = false;
        adapter.notifyDataSetChanged();
        // TODO: 17/7/29 send 广播

    }


    private void requestNickName() {


        StringBuilder builder = new StringBuilder();
        for (Conversation cs : conversationList) {
            if (cs.getWenwenName() == null) {
                builder.append(cs.getIdentify() + ",");
            }
        }
        if (builder.length() > 0) {
            final String uids = builder.substring(0, builder.length() - 1);

            NetUtil net = new NetUtil(getActivity(), JsonApi.GET_USER_INFO_FOR_CHAT);
            net.setParams("uids", uids);
            net.postRequest("", new NetUtil.RequestStringListener() {
                @Override
                public void onComplete(String result) {
String data = JSONUtil.getData(result);

                    JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
                    for (Conversation cs : conversationList) {
                        JsonObject user = jsonObject.getAsJsonObject(cs.getIdentify());
                        if (user != null) {
                            JsonArray aa = user.get("agent_mark").getAsJsonArray();
                            boolean isVerify = false;
                            for (int i = 0; i < aa.size(); i++) {
                                if (aa.get(i).getAsInt() == 6) {
                                    isVerify = true;
                                    break;
                                }
                            }
                            cs.setMyAvatar(user.get("u_avatar").getAsString());
                            cs.setWenwenName(user.get("u_realname").getAsString());
                            cs.setVerify(isVerify);
                            cs.setAgentLevel(user.get("ua_title").getAsInt());
                        }
                    }

                    adapter.notifyDataSetChanged();
                }
            });
        }
    }

    /**
     * 获取好友关系链管理系统最后一条消息的回调
     *
     * @param message     最后一条消息
     * @param unreadCount 未读数
     */
    @Override
    public void onGetFriendshipLastMessage(TIMFriendFutureItem message, long unreadCount) {
        if (friendshipConversation == null) {
            friendshipConversation = new FriendshipConversation(message);
            conversationList.add(friendshipConversation);
        } else {
            friendshipConversation.setLastMessage(message);
        }
        friendshipConversation.setUnreadCount(unreadCount);
        Collections.sort(conversationList);
        refresh();
    }

    /**
     * 获取好友关系链管理最后一条系统消息的回调
     *
     * @param message 消息列表
     */
    @Override
    public void onGetFriendshipMessage(List<TIMFriendFutureItem> message) {
        friendshipManagerPresenter.getFriendshipLastMessage();
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        Conversation conversation = conversationList.get(info.position);
        if (conversation instanceof NomalConversation) {
            menu.add(0, 1, Menu.NONE, getString(R.string.conversation_del));
        }
    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        NomalConversation conversation = (NomalConversation) conversationList.get(info.position);
        switch (item.getItemId()) {
            case 1:
                if (conversation != null) {
                    if (presenter.delConversation(conversation.getType(), conversation.getIdentify())) {
                        conversationList.remove(conversation);
                        adapter.notifyDataSetChanged();
                    }
                }
                break;
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isPrepared = false;
    }


    @Override
    public void onClick(View v) {


    }

    private void getAdviserList() {

        if (adviserAdapter == null) {

            adviserAdapter = new CommonAdapter<AgentBean>(getActivity(), adviserList, R.layout.find_adviser_item) {
                public void convert(ViewHolder holder, final AgentBean item) {
                    GlideUtil.loadCircle(getActivity(), item.ue_avatar, (ImageView) holder.getView(R.id.image_avtar));
                    holder.setText(R.id.name, item.ue_realname);

                    String verify = "";
                    int level = item.ua_title;
                    int verColor = R.color.white;
                    int drawableLeft = R.color.transparent;
                    switch (level) {
                        case 0:
                            break;
                        case 4:
                            verify = "保险管家";
                            verColor = R.color.guanja;
                            drawableLeft = R.drawable.round_corner_yellow;
                            break;
                        case 2:
                            verify = "保险精英";
                            verColor = R.color.jingying;
                            drawableLeft = R.drawable.round_corner_blue_jingying;
                            break;
                        case 1:
                            verify = "保险达人";
                            verColor = R.color.daren;
                            drawableLeft = R.drawable.round_corner_green;
                            break;
                        case 3:
                            verify = "保险专家";
                            verColor = R.color.zhuanjia;
                            drawableLeft = R.drawable.round_corner_red_zhuanjia;
                            break;
                        default:
                            break;
                    }

                    holder.getView(R.id.verify_level).setBackground(getResources().getDrawable(drawableLeft));

                    holder.setText(R.id.verify_level, verify);
                    ((TextView) holder.getView(R.id.verify_level)).setTextColor(getResources().getColor(verColor));

                    int chatStatus = item.ue_onlineStatus;
                    holder.getView(R.id.chat_status).setBackground(getResources().getDrawable(chatStatus == 0 ? R.drawable.round_corner_gray : R.drawable.round_corner_yellow));
                    ((TextView) holder.getView(R.id.chat_status)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(chatStatus == 0 ? R.drawable.one_by_one_gray : R.drawable.one_by_one), null, null, null);
                    ((TextView) holder.getView(R.id.chat_status)).setTextColor(getResources().getColor(chatStatus == 0 ? R.color.gray : R.color.yellow_lab));

                    holder.getView(R.id.chat_status).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //顾问一对一点击
                            MobclickAgent.onEvent(getActivity(), "v5_5_1_XX_1v1");
                            if (LoginInfo.getInstance(App.getContext()).isLogin()) {
                                ChatActivity.navToChat(getActivity(), item.u_id + "", TIMConversationType.C2C);
                            } else {
                                getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
                                ((Activity) getActivity()).overridePendingTransition(R.anim.slide_in_right,
                                        R.anim.slide_out_left);
                            }
                        }
                    });

                    String str = (Integer.parseInt(item.serviceCount) == 0 ? "" : (",已服务" + item.serviceCount + "投保人"));
                    holder.setText(R.id.agent_content, "从业" + item.workTime + "年" + str);


                    if (item.agent_mark != null && item.agent_mark.length > 0
                            && Arrays.asList(item.agent_mark).contains("6")) {
                        holder.getView(R.id.verify_icon).setVisibility(View.VISIBLE);
                    } else {
                        holder.getView(R.id.verify_icon).setVisibility(View.GONE);
                    }

                    holder.setText(R.id.tv_company, "机构：" + item.companyname);
                    try {
                        holder.setText(R.id.tv_distance, "地区：" + item.city);
                    } catch (Exception e) {
                    }

                    holder.getView(R.id.main).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            openActivity(AdviserActivity.class, new String[]{"params"}, new String[]{item.u_id});
                        }
                    });

                }
            };
        }

        adviserLv.setAdapter(adviserAdapter);
        if (adviserAdapter != null && adviserAdapter.getCount() > 0) {
        } else {

            NetUtil netUtil = new NetUtil(getActivity(),
                    JsonApi.RECOMMEND_AGENT);
            netUtil.setParams("pageType", 1);


            netUtil.postRequest("加载中", new NetUtil.RequestStringListener() {
                @Override
                public void onComplete(String result) {
                    if (JSONUtil.isSuccess(result)) {

                        RecommendAgentItem item = new Gson().fromJson(result, RecommendAgentItem.class);


                        adviserList.clear();

                        adviserList.addAll(item.data.list);
                        adviserAdapter.notifyDataSetChanged();
                    }
                }
            });


        }


    }


    @Override
    public void onDestroy() {
        super.onDestroy();


    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isPrepared && getUserVisibleHint()) {
            refresh();
            PushUtil.getInstance().reset();
        }
        reloadData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (!hidden) {

            if (!hidden) {
                reloadData();
                refresh();
            }
        }


    }


}
